﻿using Microsoft.AspNetCore.Mvc;
using STF.Blog.Common;
using STF.Blog.IService;
using STF.Blog.WebApp.Areas.ForumManage.Models.Comment;
using X.PagedList;

namespace STF.Blog.WebApp.Areas.ForumManage.Controllers
{
    [Area("ForumManage")]
    public class CommentController : Controller
    {
        private ICommentService _ictSvc;
        private IBlogService _blogSvc;
        private IUsersService _usersSvc;
        public CommentController(ICommentService ictSvc, IBlogService blogSvc, IUsersService usersSvc)
        {
            _ictSvc = ictSvc;
            _blogSvc = blogSvc;
            _usersSvc = usersSvc;
        }

        [HttpGet]
        public async Task<IActionResult> Index(string search, int page = 1)
        {
            search = string.IsNullOrEmpty(search) ? "" : search;
            var data = await _ictSvc.GetByNameAsync(search);
            var CommentList = new List<CommentListViewModel>();
            foreach (var item in data) 
            {
                var model = new CommentListViewModel
                {
                    Id = item.Id,
                    Content = item.Content,
                    LikeSum = item.LikeSum,
                    BlogTitle = await GetBlogTitle(item.Bid),
                    UsersTitle = await GetUsersTitle(item.Uid),
                    UpdateTime = item.UpdateTime
                };
                CommentList.Add(model);
            }

            ViewBag.Search = search;
            var pages = await CommentList.ToPagedListAsync(page,PageConfig.PageSize);
            return View(pages);
        }

        private async Task<string> GetBlogTitle(int id) 
        {
            var data = await _blogSvc.GetByIdAsync(id);
            return data == null ? "" : data.Title;
        }

        private async Task<string> GetUsersTitle(int id) 
        {
            var data = await _usersSvc.GetByIdAsync(id);
            return data == null ? "" : data.NickName;
        }

        [HttpPost]
        public async Task<IActionResult> Delete(int id) 
        {
            if (ModelState.IsValid) 
            {
                await _ictSvc.PutTrashAsync(id);
                return Redirect("~/ForumManage/Comment/Index");
            }
            return View();
        }
    }
}
